<template>
  <div class="ueditor-test-container">
    <a-card title="UEditor 测试页面" class="mb-4">
      <div class="mb-4">
        <a-button @click="initUEditor" type="primary">初始化 UEditor</a-button>
        <a-button @click="getContent" class="ml-2">获取内容</a-button>
        <a-button @click="setContent" class="ml-2">设置内容</a-button>
        <a-button @click="clearContent" class="ml-2">清空内容</a-button>
      </div>
      
      <div class="mb-4">
        <label class="block text-sm font-medium mb-2">编辑器宽度:</label>
        <div class="flex items-center space-x-4">
          <a-button @click="setWidth('100%')" size="small">100%</a-button>
          <a-button @click="setWidth('800px')" size="small">800px</a-button>
          <a-button @click="setWidth('600px')" size="small">600px</a-button>
          <a-button @click="setWidth('400px')" size="small">400px</a-button>
          <a-input 
             v-model="customWidth" 
             @pressEnter="setWidth(customWidth)"
             placeholder="自定义宽度" 
             size="small"
             style="width: 120px;"
           />
          <a-button @click="setWidth(customWidth)" type="primary" size="small">应用</a-button>
        </div>
        <p class="text-sm text-gray-600 mt-1">当前宽度: {{ currentWidth }}</p>
      </div>
      
      <div id="ueditor-container" :style="{ width: currentWidth, height: '400px' }"></div>
      
      <div class="mt-4">
        <h4>内容预览：</h4>
        <div class="content-preview" v-html="content"></div>
      </div>
    </a-card>
  </div>
</template>

<script setup lang="ts">
import { ref, onMounted, nextTick } from 'vue';
import { message } from 'ant-design-vue';

const content = ref('');
const currentWidth = ref('100%');
const customWidth = ref('');
let editor: any = null;

// 加载UEditor脚本
const loadUEditorScript = (): Promise<void> => {
  return new Promise((resolve, reject) => {
    if ((window as any).UE) {
      resolve();
      return;
    }

    // 加载UEditor配置文件
    const configScript = document.createElement('script');
    configScript.src = '/UEditor/ueditor.config.js';
    configScript.onload = () => {
      // 加载UEditor主文件
      const mainScript = document.createElement('script');
      mainScript.src = '/UEditor/ueditor.all.min.js';
      mainScript.onload = () => {
        console.log('UEditor scripts loaded successfully');
        resolve();
      };
      mainScript.onerror = () => {
        console.error('Failed to load UEditor main script');
        reject(new Error('Failed to load UEditor main script'));
      };
      document.head.appendChild(mainScript);
    };
    configScript.onerror = () => {
      console.error('Failed to load UEditor config script');
      reject(new Error('Failed to load UEditor config script'));
    };
    document.head.appendChild(configScript);
  });
};

// 初始化UEditor
const initUEditor = async () => {
  try {
    await loadUEditorScript();
    await nextTick();
    
    const UE = (window as any).UE;
    if (!UE) {
      throw new Error('UEditor not loaded');
    }

    // 销毁已存在的编辑器
    if (editor) {
      editor.destroy();
    }

    // 创建编辑器配置
    const config = {
      UEDITOR_HOME_URL: '/UEditor/',
      serverUrl: '/api/ueditor/controller',
      initialFrameWidth: '100%',
      initialFrameHeight: 400,
      autoHeightEnabled: false,
      toolbars: [[
        'fullscreen', 'source', '|', 'undo', 'redo', '|',
        'bold', 'italic', 'underline', 'strikethrough', '|',
        'forecolor', 'backcolor', '|',
        'justifyleft', 'justifycenter', 'justifyright', 'justifyjustify', '|',
        'insertorderedlist', 'insertunorderedlist', '|',
        'link', 'unlink', '|',
        'simpleupload', 'insertimage'
      ]],
      lang: 'zh-cn',
      theme: 'default'
    };

    console.log('Creating UEditor with config:', config);
    editor = UE.getEditor('ueditor-container', config);
    
    editor.ready(() => {
      console.log('UEditor is ready');
      message.success('UEditor 初始化成功');
      
      // 监听内容变化
      editor.addListener('contentChange', () => {
        content.value = editor.getContent();
      });
    });
    
  } catch (error: any) {
    console.error('Failed to initialize UEditor:', error);
    message.error('UEditor 初始化失败: ' + (error?.message || '未知错误'));
  }
};

// 获取内容
const getContent = () => {
  if (editor) {
    const editorContent = editor.getContent();
    content.value = editorContent;
    message.info(`内容长度: ${editorContent.length} 字符`);
    console.log('Editor content:', editorContent);
  } else {
    message.warning('请先初始化编辑器');
  }
};

// 设置内容
const setContent = () => {
  if (editor) {
    const testContent = '<h2>测试内容</h2><p>这是通过代码设置的<strong>富文本</strong>内容。</p>';
    editor.setContent(testContent);
    content.value = testContent;
    message.success('内容设置成功');
  } else {
    message.warning('请先初始化编辑器');
  }
};

// 清空内容
const clearContent = () => {
  if (editor) {
    editor.setContent('');
    content.value = '';
    message.success('内容已清空');
  } else {
    message.warning('请先初始化编辑器');
  }
};

// 设置编辑器宽度
const setWidth = (width: string) => {
  if (!width || width.trim() === '') {
    message.warning('请输入有效的宽度值');
    return;
  }
  
  currentWidth.value = width;
  
  if (editor) {
    // 重新设置编辑器容器的宽度
    const container = document.getElementById('ueditor-container');
    if (container) {
      container.style.width = width;
      // 触发编辑器重新计算尺寸
      setTimeout(() => {
        if (editor && editor.fireEvent) {
          editor.fireEvent('resize');
        }
      }, 100);
    }
    message.success(`编辑器宽度已设置为: ${width}`);
  } else {
    message.warning('请先初始化编辑器');
  }
};

// 组件挂载时自动初始化
onMounted(() => {
  // 延迟初始化，确保DOM完全渲染
  setTimeout(() => {
    initUEditor();
  }, 500);
});
</script>

<style scoped>
.ueditor-test-container {
  padding: 20px;
}

.content-preview {
  border: 1px solid #ddd;
  padding: 10px;
  min-height: 100px;
  background: #f9f9f9;
}

.ml-2 {
  margin-left: 8px;
}

.mb-4 {
  margin-bottom: 16px;
}

.mt-4 {
  margin-top: 16px;
}
</style>

<style>
/* UEditor 全局样式 */
.edui-default {
  z-index: 9999 !important;
}

.edui-popup {
  z-index: 10000 !important;
}

.edui-dialog {
  z-index: 10001 !important;
}
</style>